package com.seqb.common.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.seqb.common.utils.ShiroUtils;
import com.seqb.manage.user.domain.UserDO;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author lils
 * @title 属性值自动填充功能
 * @description 请填写相关描述
 * @date 2019/11/14
 */
@Component
public class FillMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        Date now = new Date();
        /**
         * 设置实体属性setter进去的值，优先级要高于自动填充的值。
         * 如果实体没有设置该属性，就给默认值，防止entity的setter值被覆盖。
         */
        Object createDate = this.getFieldValByName("createDate", metaObject);
        if (null == createDate) {
            this.setFieldValByName("createDate", now, metaObject);
        }
        Object modifyDate = this.getFieldValByName("updateDate", metaObject);
        if (null == modifyDate) {
            this.setFieldValByName("updateDate", now, metaObject);
        }
        Object version = this.getFieldValByName("version", metaObject);
        if (null == version) {
            this.setFieldValByName("version", 1L, metaObject);
        }
        Object isDelete = this.getFieldValByName("isDelete", metaObject);
        if (null == isDelete) {
            this.setFieldValByName("isDelete", "0", metaObject);
        }
        UserDO currUser = ShiroUtils.getUser();
        Object createNumber = this.getFieldValByName("createNumber", metaObject);
        if (null != currUser && null == createNumber) {
            this.setFieldValByName("createNumber", currUser.getId(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {

    }
}
